package sr.codemg.config;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import sr.codemg.utils.Constants;
import sr.codemg.vm.Login;

import java.util.Date;

@Slf4j
public class JwtConfig {

    public static String create(Login.Request entity, String role) {
        String jwtToken = Jwts.builder().setSubject(entity.getUserId())
                .setIssuedAt(new Date()).claim("role", role).claim("clientType", entity.getClientType())
                .signWith(SignatureAlgorithm.HS256, Constants.SECRETKEY).compact();
        return jwtToken;
    }

    public static String refresh(Claims claims) {
        String jwtToken = Jwts.builder().setSubject(claims.getSubject()).setIssuedAt(new Date())
                .claim("role", claims.get("role")).claim("clientType", claims.get("clientType"))
                .signWith(SignatureAlgorithm.HS256, Constants.SECRETKEY).compact();
        return jwtToken;
    }

    public static Claims thinning(String token) {
        Claims claims = Jwts.parser().setSigningKey(Constants.SECRETKEY).parseClaimsJws(token).getBody();
        return claims;
    }

    public static String getUserId(String token) {
        return thinning(token).getSubject();
    }

    public static String getUserId(Claims claims) {
        return claims.getSubject();
    }

    public static String getRoleId(Claims claims) {
        return claims.get("role", String.class);
    }

    public static String getRoleId(String token) {
        return thinning(token).get("role", String.class);
    }
}